package io.gitee.minelx.commontools.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public final class Clocks {
    public static Clock now(ClockUnit unit) {
        return now().cast(unit);
    }

    public static Clock now() {
        return new Clock(Calendar.getInstance());
    }

    public static Clock text(String format, String text) {
        return millis(parseFormatToMillis(format, text));
    }

    public static Clock unixTime(int unixTime) {
        return millis(unixTime * 1000L);
    }

    public static Clock millis(long millis) {
        Calendar result = Calendar.getInstance();
        result.setTime(new Date(millis));
        return new Clock(result);
    }

    static Calendar copy(Calendar source) {
        Calendar result = Calendar.getInstance();
        result.set(source.get(Calendar.YEAR),
                source.get(Calendar.MONTH),
                source.get(Calendar.DAY_OF_MONTH),
                source.get(Calendar.HOUR_OF_DAY),
                source.get(Calendar.MINUTE),
                source.get(Calendar.SECOND));
        result.set(Calendar.MILLISECOND, source.get(Calendar.MILLISECOND));
        return result;
    }

    private static long parseFormatToMillis(String format, String text) {
        try {
            return new SimpleDateFormat(format).parse(text).getTime();
        } catch (ParseException e) {
            throw new RuntimeException("something is wrong here", e);
        }
    }
}
